package cn.llk.mall.controller.api;


import cn.llk.mall.entity.GoodsEntity;
import cn.llk.mall.entity.GoodsOrderEntity;
import cn.llk.mall.entity.UserEntity;
import cn.llk.mall.entity.vo.GoodsOrderVO;
import cn.llk.mall.service.GoodsOrderService;
import cn.llk.mall.service.GoodsService;
import cn.llk.mall.util.HttpResult;
import cn.llk.mall.util.RedisUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author llk
 * @since 2021-04-20
 */
@RestController
@RequestMapping("/goods")
@Api(value = "商品接口")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    GoodsOrderService goodsOrderService;

    /**
     * @Description: 购物车
     *         cart:userID
     * @Description: goodsId：count
     */
    public static final String cart_prefix = "cart:";

    @GetMapping("/getOrderHistory")
    public HttpResult<?> getOrderHistory(HttpServletRequest request) {
        UserEntity user = (UserEntity) request.getSession().getAttribute("user");
        List<GoodsOrderEntity> list = goodsOrderService.listByUserId(user.getId());
        return HttpResult.ok(list);
    }

    /**
     * 清空购物车
     *
     * @param request 请求
     * @return {@link HttpResult<?>}
     */
    @PostMapping("/buyCart")
    public HttpResult<?> buyCart(HttpServletRequest request) {
        UserEntity user = (UserEntity) request.getSession().getAttribute("user");
        if (Objects.isNull(user)) return null;

        String userId = user.getId();
        GoodsOrderVO vos = goodsService.buyCart(redisUtil.hGetAll(cart_prefix + userId), userId);
        request.getSession().setAttribute("data", vos);
        return HttpResult.ok(vos, "购买成功!");
    }


    /**
     * 从购物车删除购物项
     *
     * @param userId  用户id
     * @param goodsId 商品id
     * @return {@link HttpResult<?>}
     */
    @PostMapping("/removeFromCart/{userId}/{goodsId}")
    public HttpResult<?> removeFromCart(@PathVariable String userId, @PathVariable String goodsId) {
        String key = cart_prefix + userId;
        redisUtil.hDelete(key, goodsId);
        GoodsOrderVO vos = goodsService.getCart(redisUtil.hGetAll(key), userId);
        return HttpResult.ok(vos);
    }

    /**
     * 获取购物车信息
     *
     * @param userId 用户id
     * @return {@link HttpResult<?>}
     */
    @GetMapping("/getCart/{userId}")
    public HttpResult<?> getCart(@PathVariable String userId) {
        String key = cart_prefix + userId;
        // goodsId : count
        Map<Object, Object> goodsIdMapCount = redisUtil.hGetAll(key);

        GoodsOrderVO vos = goodsService.getCart(goodsIdMapCount, userId);
        System.out.println(vos);
        return HttpResult.ok(vos);
    }

    /**
     * 添加到购物车
     *
     * @param goodsId 商品id
     * @param count   数量
     * @param request http {@link HttpServletRequest}
     * @return {@link HttpResult<?>}
     */
    @GetMapping("/addToCart/{goodsId}/{count}")
    public HttpResult<?> addToCart(@PathVariable String goodsId, @PathVariable Integer count, HttpServletRequest request) {
        UserEntity user = ((UserEntity) request.getSession().getAttribute("user"));
        if (Objects.isNull(user)) {
            return HttpResult.error(null, "用户位登录，请登录", 101);
        }
        goodsService.putInCart(goodsId, count, user);
        return HttpResult.ok("添加成功");
    }


    /**
     * 在商品详情页面直接购买 - 直接结算
     *
     * @param count   购买数量
     * @param goodsId 商品id
     * @return {@link HttpResult<?>}
     */
    @GetMapping("/buy/{goodsId}/{count}")
    public HttpResult<?> buy(@PathVariable Integer count, @PathVariable String goodsId, HttpServletRequest request) {
        UserEntity user = ((UserEntity) request.getSession().getAttribute("user"));
        if (Objects.isNull(user)) {
            return HttpResult.error(null, "用户位登录，请登录", 101);
        }
        GoodsEntity goods = goodsService.checkStock(goodsId, count);
        if (Objects.isNull(goods)) return HttpResult.error(null, "库存不足", 202);

        GoodsOrderVO vo = goodsService.buy(goods, count, user);
        // 保存到session中
        request.getSession().setAttribute("data", vo);
        return HttpResult.ok(vo, "购买成功");
    }

    /**
     * 添加商品
     *
     * @param goods 商品
     * @return {@link HttpResult<?>}
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加商品", notes = "添加商品")
    public HttpResult<?> add(@RequestBody GoodsEntity goods) {
        goods.setCreateDate(new Date());
        goods.setUpdateDate(new Date());
        goodsService.save(goods);
        return HttpResult.ok("添加成功");
    }

    /**
     * 列表
     *
     * @param no        current page no
     * @param size      page size
     * @param goodsName 商品名称
     * @param goodsType 商品类型
     * @return {@link HttpResult<?>}
     */
    @GetMapping("/list/{no}/{size}")
    public HttpResult<?> list(@PathVariable long no,
                              @PathVariable long size,
                              String goodsName, String goodsType) {
        IPage<GoodsEntity> page = goodsService.findPage(no, size, goodsName, goodsType);
        return HttpResult.ok(page);
    }

    /**
     * 查看
     *
     * @param goodsId 商品id
     * @return {@link HttpResult<?>}
     */
    @GetMapping("/view/{goodsId}")
    public HttpResult<?> view(@PathVariable String goodsId) {
        GoodsEntity dbGoods = goodsService.getById(goodsId);
        return HttpResult.ok(dbGoods);
    }
}

